package filter

import (
	"bytes"
	"strings"

	"gitee.com/gousing/helper/internal/emoji"
)

// StripEmoji 过滤掉表情符号
func StripEmoji(s string) string {
	if len(strings.TrimSpace(s)) < 1 {
		return s
	}
	return StripEmojiFunc(s, nil)
}

// StripEmojiFunc 自定义函数过滤掉表情符号
func StripEmojiFunc(s string, f func(emoji string) string) string {
	var buff bytes.Buffer
	buff.Grow(len(s))
	nextIndex := 0
	for i, r := range s {
		if i < nextIndex {
			continue
		}

		match, length := emoji.AllSequences.HasEmojiPrefix(s[i:])
		if !match {
			buff.WriteRune(r)
			continue
		}

		nextIndex = i + length
		if f != nil {
			re := f(s[i : i+length])
			if re != "" {
				buff.WriteString(re)
			}
		}
	}

	return buff.String()
}
